import io
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
from finder import Finder
import tools
import pytesseract
from PIL import Image
import gc


class PPTFinder(Finder):
    @staticmethod
    def file_suffixes():
        return [".pptx"]

    def search_file(self, file_path, search_content):

        slide_number = 1
        prs = Presentation(file_path)
        for slide in prs.slides:
            slide_content = ""
            for shape in slide.shapes:
                if shape.is_placeholder:
                    if shape.has_text_frame:
                        for paragraph in shape.text_frame.paragraphs:
                            for run in paragraph.runs:
                                # print(f"ppt_text:{run.text}")
                                slide_content += run.text.replace('\n', '')
                elif shape.has_text_frame:
                    for paragraph in shape.text_frame.paragraphs:
                        for run in paragraph.runs:
                            # print(f"ppt_text2: {run.text}")
                            slide_content += run.text.replace('\n', '')
                elif shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
                    # TODO: 这里要加try catch
                    try:
                        image_txt = pytesseract.image_to_string(Image.open(io.BytesIO(shape.image.blob)), "chi_sim")
                        # print(f"ppt:image_text:{image_txt}")
                        slide_content += image_txt.replace('\n', '')
                    except Exception as e:
                        print("Error: PPT中图片处理发生了异常")

            slide_number += 1

            with tools.lock:
                tools.global_store[f"{file_path} slide {slide_number}"] = slide_content
            pass

            if search_content in Finder.process_text_if_need(slide_content.lower()):
                print(f"Found {search_content} in {file_path} slide {slide_number}")

        del prs
        gc.collect()
